package com.dmtest.netty_learn.chapter13;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

/**
 * Created by dimi on 2018/12/12.
 */
public class LogEventBroadcaster {

    private final EventLoopGroup group;
    private final Bootstrap bootstrap;
    private final File file;

    public LogEventBroadcaster(InetSocketAddress address,File file){
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST,true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new LogEventEncoder(address));
                    }
                });
        this.file = file;
    }

    public void run() throws IOException{
        Channel ch = bootstrap.bind(0).syncUninterruptibly().channel();
        long pointer = 0;
        for (;;) {
            long len = file.length();
            if(len < pointer) {
                // file was reset
                pointer = len;
            } else if(len > pointer) {
                // content was added
                RandomAccessFile raf = new RandomAccessFile(file,"r");
                raf.seek(pointer);
                String line;
                while((line = raf.readLine()) != null) {
                    System.out.println(" broadcaster: line-> " + line);
                    ch.writeAndFlush(new LogEvent(null,-1,file.getAbsolutePath(),line));
                    pointer = raf.getFilePointer();
                }
                raf.close();
                try{
                    Thread.sleep(1000);
                }catch (Exception e) {
                    Thread.interrupted();
                    break;
                }
            }
        }
    }

    public void stop(){
        group.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception{
        int port = 8888;
        File file = new File("D:\\oschinagit\\netty_learn\\src\\main\\java\\com\\dmtest\\netty_learn\\chapter13\\hello.txt");
        LogEventBroadcaster broadcaster = new LogEventBroadcaster(new InetSocketAddress("255.255.255.255",port),file);
        try{
            broadcaster.run();
        }finally {
            broadcaster.stop();
        }

    }


}
